<?php

namespace App\Http\Controllers;

use App\Models\MoneyCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use App\Models\MoneyBook;
use App\Models\MoneyBookUser;

class UserBookController extends Controller
{
    /**
     * 显示用户账本列表
     */
    public function index()
    {
        $user = Auth::user();

        // 获取用户参与的所有账本
        $books = $user->books()->with('creator')->get();

        // 获取用户创建的账本
        $createdBooks = $user->createdBooks()->get();

        return view('user.account-books', compact('books', 'createdBooks', 'user'));
    }

    /**
     * 设置默认账本
     */
    public function setDefault(Request $request, $id)
    {
        $user = Auth::user();

        // 验证账本ID是否有效
        if (!is_numeric($id)) {
            return response()->json([
                'success' => false,
                'message' => '无效的账本ID'
            ], 422);
        }

        // 验证用户是否有权限访问该账本
        $book = MoneyBook::where('id', $id)
            ->where(function($query) use ($user) {
                $query->where('user_id', $user->id)
                      ->orWhereHas('users', function($q) use ($user) {
                          $q->where('user_id', $user->id);
                      });
            })->first();

        if (!$book) {
            return response()->json([
                'success' => false,
                'message' => '您没有权限访问该账本'
            ], 403);
        }

        try {
            // 更新用户的默认账本
            $user->update([
                'default_book_id' => $id
            ]);

            return response()->json([
                'success' => true,
                'message' => '默认账本设置成功',
                'book' => [
                    'id' => $book->id,
                    'name' => $book->name
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '设置失败，请重试'
            ], 500);
        }
    }

    /**
     * 更新账本信息
     */
    public function update(Request $request, $id)
    {
        $user = Auth::user();

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:50',
            'description' => 'nullable|string|max:255',
            'icon' => 'nullable|string|max:10',
        ], [
            'name.required' => '账本名称不能为空',
            'name.max' => '账本名称不能超过50个字符',
            'description.max' => '账本描述不能超过255个字符',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        // 验证用户是否有权限编辑该账本（只有创建者或管理员可以编辑）
        $book = MoneyBook::where('id', $id)
            ->where(function($query) use ($user) {
                $query->where('user_id', $user->id)
                      ->orWhereHas('users', function($q) use ($user) {
                          $q->where('user_id', $user->id)
                            ->where('role', 'admin');
                      });
            })->first();

        if (!$book) {
            return response()->json([
                'success' => false,
                'message' => '您没有权限编辑该账本'
            ], 403);
        }

        try {
            $data = [
                'name' => $request->name,
                'description' => $request->description,
            ];
            if ($request->icon) $data['icon'] = $request->icon;
            $book->update($data);

            return response()->json([
                'success' => true,
                'message' => '账本更新成功',
                'book' => [
                    'id' => $book->id,
                    'name' => $book->name,
                    'description' => $book->description,
                    'icon' => $book->icon,
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '更新失败，请重试'
            ], 500);
        }
    }

    /**
     * 删除账本
     */
    public function destroy($id)
    {
        $user = Auth::user();

        // 验证用户是否有权限删除该账本（只有创建者可以删除）
        $book = MoneyBook::where('id', $id)
            ->where('user_id', $user->id)
            ->first();

        if (!$book) {
            return response()->json([
                'success' => false,
                'message' => '您没有权限删除该账本'
            ], 403);
        }

        // 检查是否为用户的默认账本
        if ($user->default_book_id == $book->id) {
            // 如果是默认账本，需要先设置其他账本为默认
            $otherBook = $user->books()->where('book_id', '!=', $book->id)->first();
            if ($otherBook) {
                $user->update(['default_book_id' => $otherBook->id]);
            } else {
                $user->update(['default_book_id' => null]);
            }
        }

        try {
            // 删除相关数据
            $book->transactions()->delete();
            $book->categories()->delete();
            $book->users()->detach();
            $book->delete();

            return response()->json([
                'success' => true,
                'message' => '账本删除成功'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '删除失败，请重试'
            ], 500);
        }
    }

    /**
     * 离开账本
     */
    public function leave($id)
    {
        $user = Auth::user();

        // 验证用户是否参与了该账本
        $bookUser = MoneyBookUser::where('book_id', $id)
            ->where('user_id', $user->id)
            ->first();

        if (!$bookUser) {
            return response()->json([
                'success' => false,
                'message' => '您不在该账本中'
            ], 404);
        }

        // 检查用户是否为账本创建者
        $book = MoneyBook::find($id);
        if ($book && $book->user_id == $user->id) {
            return response()->json([
                'success' => false,
                'message' => '创建者不能离开自己的账本，请删除账本'
            ], 403);
        }

        // 检查是否为用户的默认账本
        if ($user->default_book_id == $id) {
            // 如果是默认账本，需要先设置其他账本为默认
            $otherBook = $user->books()->where('book_id', '!=', $id)->first();
            if ($otherBook) {
                $user->update(['default_book_id' => $otherBook->book_id]);
            } else {
                $user->update(['default_book_id' => null]);
            }
        }

        try {
            // 从账本中移除用户
            $bookUser->delete();

            return response()->json([
                'success' => true,
                'message' => '已成功离开账本'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '离开失败，请重试'
            ], 500);
        }
    }
}
